package com.moyu.admin.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moyu.admin.bean.BaseReq;
import com.moyu.admin.bean.BaseResp;
import com.moyu.admin.service.IUserInfoService;
import com.moyu.data.domain.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 前端控制器
 *
 * @author makun
 * @since 2019-02-22
 */
@Controller
@RequestMapping("/admin/user")
@Slf4j
@Api("用户管理")
public class UserInfoController extends BaseController{

  @Autowired private IUserInfoService userInfoService;

  @RequestMapping("/index")
  public String index() {
    return "/admin/user/index";
  }

  @RequestMapping("/list")
  @ResponseBody
  @ApiOperation(value = "用户列表")
  public Map<String, Object> list(BaseReq req) {
    IPage<UserInfo> page =
        userInfoService.page(new Page<>(req.getPage(), req.getRows()), new QueryWrapper<>());
    Map<String, Object> resultMap = new HashMap();
    resultMap.put("rows", page.getRecords());
    resultMap.put("total", page.getTotal());
    return resultMap;
  }

  @PostMapping("/add")
  @ResponseBody
  public BaseResp<UserInfo> add(UserInfo userInfo) {
    userInfo.setCreateUser(getCurrentUser().getId());
    userInfo.setCreateTime(LocalDateTime.now());
    userInfoService.addUser(userInfo);
    return BaseResp.success();
  }

  @PostMapping("/edit")
  @ResponseBody
  public BaseResp<UserInfo> edit(UserInfo userInfo) {
    userInfo.setUpdateUser(getCurrentUser().getId());
    userInfo.setUpdateTime(LocalDateTime.now());
    userInfoService.updateById(userInfo);
    return BaseResp.success();
  }

  @PostMapping("/del")
  @ResponseBody
  public BaseResp<UserInfo> del(Long id) {
    userInfoService.removeById(id);
    return BaseResp.success();
  }
}
